# ...existing code...
import datetime

from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
import logging
from .pp_py.django_pp import django_pp, dbz_pp
from .pp_py.visualize_grids import get_grids_info

logger = logging.getLogger(__name__)

# 定义一个视图函数，接收请求对象request
@csrf_exempt
def pp_view(request):
    try:
        # 解析请求体
        body_bytes = request.body or b''
        body_text = body_bytes.decode('utf-8') if body_bytes else ''
        data = json.loads(body_text) if body_text else {}
        # 从解析后的 JSON 中取出 data 字段
        data_field = data.get('data', {}) if isinstance(data, dict) else {}
        current_time = datetime.datetime.now().strftime("%d/%b/%Y %H:%M:%S")
        print(f"[{current_time}] /pp/接收到前端请求数据: {data_field}")
        # 解析数据
        start_obj = data_field.get('start') or {}
        end_obj = data_field.get('end') or {}
        waypoints_obj = data_field.get('waypoints') or []
        constraints_obj = data_field.get('constraints') or []
        priority_obj = data_field.get('priority') or ''
        noentryarea_obj = data_field.get('noEntryArea') or []
        # 进一步解析
        start_tuple = (float(start_obj.get('lat')), float(start_obj.get('lon')))
        end_tuple = (float(end_obj.get('lat')), float(end_obj.get('lon')))
        waypoints = [(float(wp['lat']), float(wp['lng'])) for wp in waypoints_obj]
        constraints = [int(item) for item in constraints_obj]
        priority = int(priority_obj)
        noentryareas = []
        for area_points in noentryarea_obj:
            # 每个禁行区由多个点组成
            area_coords = [(float(point['lat']), float(point['lon'])) for point in area_points]
            noentryareas.append(area_coords)
        return JsonResponse({
            'status': 'ok',
            'data': django_pp(
                start=start_tuple,
                end=end_tuple,
                waypoints=waypoints,
                constraints=constraints,
                priority=priority,
                noentryareas=noentryareas)
            },
            json_dumps_params={'ensure_ascii': False}
        )
    except Exception as e:
        logger.exception("Error parsing request body")
        print("Error parsing request body:", e)
        return HttpResponse("Error parsing request body: " + str(e), status=400)

@csrf_exempt
def cells_view(request):
    try:
        # 解析请求体
        body_bytes = request.body or b''
        body_text = body_bytes.decode('utf-8') if body_bytes else ''
        data = json.loads(body_text) if body_text else {}
        # 从解析后的 JSON 中取出 data 字段
        data_field = data.get('data', {}) if isinstance(data, dict) else {}
        current_time = datetime.datetime.now().strftime("%d/%b/%Y %H:%M:%S")
        print(f"[{current_time}] /cells/接收到前端请求数据: {data_field}")
        # 解析数据
        h3indexes = data_field.get('h3indexes') or []
        return JsonResponse({
            'status': 'ok',
            'data': get_grids_info(h3indexes)
        },
            json_dumps_params={'ensure_ascii': False}
        )
    except Exception as e:
        logger.exception("Error parsing request body")
        print("Error parsing request body:", e)
        return HttpResponse("Error parsing request body: " + str(e), status=400)

@csrf_exempt
def dbz_view(request):
    try:
        # 解析请求体
        body_bytes = request.body or b''
        body_text = body_bytes.decode('utf-8') if body_bytes else ''
        data = {}
        if body_text.strip():
            try:
                data = json.loads(body_text)
            except json.JSONDecodeError as je:
                logger.exception("Invalid JSON format")
                print("Invalid JSON format:", je)
                return HttpResponse("Invalid JSON format: " + str(je), status=400)

        # 从解析后的 JSON 中取出 data 字段
        data_field = data.get('data', {}) if isinstance(data, dict) else {}
        current_time = datetime.datetime.now().strftime("%d/%b/%Y %H:%M:%S")
        print(f"[{current_time}] /dbz/接收到前端请求数据: {data_field}")

        # 解析各个位置信息
        qdwz = data_field.get('qdwz', {})
        zkwz = data_field.get('zkwz', {})
        skwz = data_field.get('skwz', {})
        # 转换为元组
        qdwz_tuple = (float(qdwz.get('lat', 0)), float(qdwz.get('lon', 0)))
        zkwz_tuple = (float(zkwz.get('lat', 0)), float(zkwz.get('lon', 0)))
        skwz_tuple = (float(skwz.get('lat', 0)), float(skwz.get('lon', 0)))

        return JsonResponse({
            'status': 'ok',
            'data': dbz_pp(
            qdwz=qdwz_tuple,
            zkwz=zkwz_tuple,
            skwz=skwz_tuple)
        },
            json_dumps_params={'ensure_ascii': False}
        )
    except Exception as e:
        logger.exception("Error parsing request body")
        print("Error parsing request body:", e)
        return HttpResponse("Error parsing request body: " + str(e), status=400)
